﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using Microsoft.Expression.Interactivity.Layout;

namespace StrategyMap
{
    public class ConnectBehavior : Behavior<UserControl>
    {
        public string ConnectTo { get; set; }
        public int StrokeThickness { get; set; }
        public bool DropShadow { get; set; }
        public double BendAmount { get; set; }
        public double ArrowSize { get; set; }
        public string ArrowType { get; set; }
        public SolidColorBrush Color { get; set; }
        public DoubleCollection StrokeDashArray { get; set; }

        public ConnectBehavior()
        {
            StrokeThickness = 2;
            ArrowType = "Default";
        }

        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.Loaded += Loaded;
            AssociatedObject.MouseMove += MouseMove;
        }

        void MouseMove(object sender, MouseEventArgs e)
        {
            if (String.IsNullOrEmpty(ConnectTo) == false)
            {
                var connectToElement = (AssociatedObject.Parent as Panel).FindName(ConnectTo) as UserControl;
                Connections.Adjust(AssociatedObject, connectToElement);
            }
            else
            {
                Connections.Adjust(AssociatedObject);
            }
        }

        void Loaded(object sender, RoutedEventArgs e)
        {
            if (String.IsNullOrEmpty(ConnectTo) == false)
            {
                var connectToElement = (AssociatedObject.Parent as Panel).FindName(ConnectTo) as UserControl;

                //wire up drag behavior for source 'From' element
                Interaction.GetBehaviors(AssociatedObject).Add(new MouseDragElementBehavior());

                //wire up drag behavior for destination 'To' element
                Interaction.GetBehaviors(connectToElement).Add(new MouseDragElementBehavior());

                //wire up connect behavior for destination 'To' element
                Interaction.GetBehaviors(connectToElement).Add(new ConnectBehavior());

                Connections.Add(AssociatedObject, connectToElement, Color, StrokeThickness, BendAmount, ArrowSize,
                                StrokeDashArray, ArrowType, DropShadow);
            }
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.Loaded -= Loaded;
            AssociatedObject.MouseMove -= MouseMove;
        }
    }
}
